/**
 * @filename:SysActionController 2022年1月27日
 * @project Wonder xhadmin Framework  V1.0
 * Copyright(c) 2020 LuZhongren Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.admin.controller;

import com.wonder.admin.constant.Parameters;
import com.wonder.admin.domain.SysAction;
import com.wonder.admin.domain.SysApplication;
import com.wonder.admin.domain.SysMenu;
import com.wonder.admin.domain.SysUploadConfig;
import com.wonder.admin.service.SysActionService;
import com.wonder.admin.service.SysApplicationService;
import com.wonder.admin.service.SysFieldService;
import com.wonder.admin.service.SysMenuService;
import com.wonder.admin.service.SysUploadConfigService;
import com.wonder.admin.request.SysActionRequest;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wonder.common.common.AjaxMap;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.bean.BeanUtils;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * <p>
 * 说明： 模块方法管理API接口层
 * </P>
 * 
 * @version: V1.0
 * @author: LuZhongren
 * @time 2022年1月27日
 *
 */
@Api(tags = "模块方法管理")
@RestController
@RequestMapping("/admin/Sys.Base")
public class SysActionController {

	@Autowired
	private SysActionService sysActionService;

	@Autowired
	private SysMenuService sysMenuService;

	@Autowired
	private SysFieldService sysFieldService;
	
	@Autowired
	private SysApplicationService sysApplicationService;
	
	@Autowired
	private SysUploadConfigService sysUploadService;
	


	@ApiOperation(value = "模块方法管理列表")
	@RequestMapping(value = "/actionList", method = RequestMethod.POST)
	public Map<String, Object> actionList(@RequestBody SysActionRequest sysActionRequest) {

		Long menu_id = sysActionRequest.getMenu_id();
		if (menu_id == null)
			return AjaxMap.failed(MessageUtils.message("input.parameter.error"));
		Page<SysAction> page = new Page<SysAction>(sysActionRequest.getPage(), sysActionRequest.getLimit());
		IPage<SysAction> list = sysActionService.selectList(sysActionRequest, page);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", CommonPage.restPage(list));
		map.put("actionList", Parameters.actionList());
		map.put("menu_title", sysMenuService.getById(menu_id).getTitle());

		return AjaxMap.success(map);
	}

	/**
	 * @explain 查询对象 <swagger GET请求>
	 * @param 对象参数：id
	 * @return JsonResult
	 * @author LuZhongren
	 * @time 2022年1月27日
	 */
	@PostMapping("/getActionInfo")
	@ApiOperation(value = "获取模块方法管理对象", notes = "作者：LuZhongren")
	public AjaxResult<SysAction> getActionInfo(@RequestBody Map<String, Object> map) {
		if (map == null)
			return AjaxResult.failed(MessageUtils.message("search.not.exist"));
		long id = Long.parseLong(map.get("id").toString());
		long menu_id = Long.parseLong(map.get("menu_id").toString());

		SysAction sysAction = sysActionService.getById(id);
		if (sysAction == null)
			return AjaxResult.failed(MessageUtils.message("search.not.exist"));
		List<String> columns = sysFieldService.getFieldList(menu_id);

		if (sysAction.getTab_config_table() != null) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> tab_config_items = JSON.parseObject(sysAction.getTab_config_table(),
					new ArrayList<Map<String, Object>>().getClass());
			sysAction.setTab_config(tab_config_items);
		}

		if (sysAction.getList_filter_table() != null) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> list_filter_items = JSON.parseObject(sysAction.getList_filter_table(),
					new ArrayList<Map<String, Object>>().getClass());
			sysAction.setList_filter(list_filter_items);
		}

		if (sysAction.getWith_join_table() != null) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> with_join_items = JSON.parseObject(sysAction.getWith_join_table(),
					new ArrayList<Map<String, Object>>().getClass());
			sysAction.setWith_join(with_join_items);
		}
		String[] field_post = StringUtils.split(sysAction.getFields_table(), ",");
		if (field_post != null) {
			List<String> fields = Arrays.asList(field_post);
			if (field_post != null && field_post.length > 0) {
				for (String field : field_post) {
					if (!columns.contains(field))
						if(fields.contains(field))fields.remove(field);
				}
				sysAction.setFields(fields.toArray(new String[] {}));
			}
		}

		return AjaxResult.success(sysAction);

	}

	/**
	 * @explain 删除对象
	 * @param 对象参数：id
	 * @return JsonResult
	 * @author LuZhongren
	 * @time 2022年1月27日
	 */
	@PostMapping("/deleteAction")
	@ApiOperation(value = "删除", notes = "作者：LuZhongren")
	public AjaxResult<SysAction> deleteAction(@RequestBody Map<String, Object> map) {
		if (map == null)
			return AjaxResult.failed(MessageUtils.message("search.not.exist"));
		String ids = map.get("id").toString();
		String[] fieldIds = StringUtils.split(ids, ',');
		List<Long> idList = new ArrayList<>();
		for (int i = 0; i < fieldIds.length; i++) {
			idList.add(Long.parseLong(fieldIds[i]));// 整数数组
		}
		List<SysAction> sysActions = sysActionService.listByIds(idList);

		if (null != sysActions) {
			boolean rsg = sysActionService.removeBatchByIds(idList);
			if (rsg) {
				return AjaxResult.success(MessageUtils.message("delete.success"));
			} else {
				return AjaxResult.failed(MessageUtils.message("delete.fail"));
			}
		} else {
			return AjaxResult.failed(MessageUtils.message("delete.not.exist"));
		}
	}

	/**
	 * @explain 添加
	 * @param 对象参数：SysAction
	 * @return Boolean
	 * @author LuZhongren
	 * @time 2022年1月27日
	 */
	@PostMapping("/createAction")
	@ApiOperation(value = "添加", notes = "作者：LuZhongren")
	public AjaxResult<SysAction> createAction(@RequestBody SysAction entity) {

		if (entity == null)
			return AjaxResult.failed(MessageUtils.message("input.parameter.error"));
		// Check has the same action name or not
		if (StringUtils.isBlank(entity.getAction_name()))
			return AjaxResult.failed(MessageUtils.message("input.parameter.error"));
		long count = sysActionService.count(new QueryWrapper<SysAction>().eq("action_name", entity.getAction_name()).eq("menu_id", entity.getMenu_id()));
		if (count > 0)
			return AjaxResult.failed(MessageUtils.message("same.name.record.is.existed"));
		if (entity.getWith_join() != null) {
			List<Map<String, Object>> with_joins = entity.getWith_join();
			if( with_joins.size()>0)
			{
				for (Map<String, Object> item : with_joins) {
					SysMenu menu = sysMenuService.getOne(new QueryWrapper<SysMenu>()
							.eq("controller_name", item.get("relative_table").toString()).select("connect", "table_name"));
					item.put("table_name", menu.getTable_name());
					item.put("connect", menu.getConnect());
	
				}
				String with_join_table=JSON.toJSONString(entity.getWith_join());
				if(with_join_table.equals("null"))
					entity.setWith_join_table(null);
				else {
				entity.setWith_join_table(with_join_table);	
				}
			}
		}
		if(entity.getList_filter()!=null && entity.getList_filter().size()>0)
		    entity.setList_filter_table(JSON.toJSONString(entity.getList_filter()));
		if(entity.getTab_config()!=null && entity.getTab_config().size()>0)
		    entity.setTab_config_table(JSON.toJSONString(entity.getTab_config()));

		entity.setFields_table(StringUtils.join(entity.getFields(), ","));
		
		int[] types = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18,21 };
		for (int i = 0; i < types.length; i++) {
			if (entity.getType() == types[i]) {
				entity.setGroup_button_status(1);
				break;
			}
		}

		if (entity.getType() == 2 || entity.getType() == 3 || entity.getType() == 21)
			entity.setDialog_size("600px");
		if (entity.getType() == 4 || entity.getType() == 3 || entity.getType() == 21)
			entity.setList_button_status(1);
		// Later if need, we will deal following matter
//		$data['other_config'] = json_encode($data['other_config']);
//		$data['sql'] = sql_replace($data['sql']);
		String validate=sysActionService.validate(entity);
		if(validate!=null) return AjaxResult.failed(validate);
		boolean rsg = sysActionService.save(entity);
		if (rsg) {
			// Update the sortid the same as the key id
			sysActionService
					.update(new UpdateWrapper<SysAction>().set("sortid", entity.getId()).eq("id", entity.getId()));
			return AjaxResult.success(MessageUtils.message("insert.success"));
		} else {
			return AjaxResult.failed(MessageUtils.message("insert.fail"));
		}
	}
	
	
	

	/**
	 * @explain 修改
	 * @param 对象参数：SysAction
	 * @return Boolean
	 * @author LuZhongren
	 * @time 2022年1月27日
	 */
	@PostMapping("/updateAction")
	@ApiOperation(value = "修改", notes = "作者：LuZhongren")
	public AjaxResult<SysAction> updateAction(@RequestBody SysAction entity) {
		if (null != entity) {
			if (entity.getWith_join() != null) {
				List<Map<String, Object>> with_joins = entity.getWith_join();
				for (Map<String, Object> item : with_joins) {
					SysMenu menu = sysMenuService.getOne(new QueryWrapper<SysMenu>()
							.eq("controller_name", item.get("relative_table").toString()).select("connect", "table_name"));
					item.put("table_name", menu.getTable_name());
					item.put("connect", menu.getConnect());

				}
			}
			if(entity.getWith_join()!=null && entity.getWith_join().size()>0)
			   entity.setWith_join_table(JSON.toJSONString(entity.getWith_join()));
			else {
				entity.setWith_join_table(null);
			}
			
			if(entity.getList_filter()!=null && entity.getList_filter().size()>0) {
			    entity.setList_filter_table(JSON.toJSONString(entity.getList_filter()));
			    }else {
			    	 entity.setList_filter_table(null);
				}
			
			if(entity.getTab_config()!=null && entity.getTab_config().size()>0)
			    entity.setTab_config_table(JSON.toJSONString(entity.getTab_config()));
			else {
				entity.setTab_config_table(null);
			}
			//entity.setList_filter_table(JSON.toJSONString(entity.getList_filter()));
			//entity.setTab_config_table(JSON.toJSONString(entity.getTab_config()));

			entity.setFields_table(StringUtils.join(entity.getFields(), ","));
			String validate=sysActionService.validate(entity);
			if(validate!=null) return AjaxResult.failed(validate);
			boolean rsg = sysActionService.updateById(entity);
			if (rsg) {
				return AjaxResult.success(MessageUtils.message("update.success"));
			} else {
				return AjaxResult.failed(MessageUtils.message("update.fail"));
			}
		} else {
			return AjaxResult.failed(MessageUtils.message("update.not.exist"));
		}
	}

	/**
	 * @explain 修改
	 * @param 对象参数：SysAction
	 * @return Boolean
	 * @author LuZhongren
	 * @time 2022年1月27日
	 */
	@PostMapping("/updateActionExt")
	@ApiOperation(value = "修改", notes = "作者：LuZhongren")
	public AjaxResult<SysAction> updateActionExt(@RequestBody SysAction entity) {
		if (null != entity) {
			if (entity.getWith_join() != null) {
				List<Map<String, Object>> with_joins = entity.getWith_join();
				for (Map<String, Object> item : with_joins) {
					SysMenu menu = sysMenuService.getOne(
							new QueryWrapper<SysMenu>().eq("controller_name", item.get("relative_table").toString())
									.select("connect", "table_name"));
					item.put("table_name", menu.getTable_name());
					item.put("connect", menu.getConnect());

				}
			}
			if(entity.getWith_join()!=null && entity.getWith_join().size()>0)
		    	entity.setWith_join_table(JSON.toJSONString(entity.getWith_join()));
			
			if(entity.getList_filter()!=null && entity.getList_filter().size()>0)
			    entity.setList_filter_table(JSON.toJSONString(entity.getList_filter()));
			
			if(entity.getTab_config()!=null && entity.getTab_config().size()>0)
			   entity.setTab_config_table(JSON.toJSONString(entity.getTab_config()));

			if(entity.getFields()!=null)
			   entity.setFields_table(StringUtils.join(entity.getFields(), ","));
			
			boolean rsg = sysActionService.updateEx(entity) > 0 ? true : false;
			if (rsg) {
				return AjaxResult.success(MessageUtils.message("update.success"));
			} else {
				return AjaxResult.failed(MessageUtils.message("update.fail"));
			}
		} else {
			return AjaxResult.failed(MessageUtils.message("update.not.exist"));
		}
	}
	
	/**
	 * @explain 修改
	 * @param 对象参数：SysAction
	 * @return Boolean
	 * @author LuZhongren
	 * @time 2022年1月27日
	 */
	@PostMapping("/getUploadList")
	@ApiOperation(value = "修改", notes = "作者：LuZhongren")
	public Map<String, Object> getUploadList(Map<String, Object> map) {
		List<SysUploadConfig> list=sysUploadService.list();
		Integer app_type=null;
		if (null != map && map.containsKey("app_id")) {
			long app_id=Long.parseLong(map.get("app_id").toString());
			SysApplication app=sysApplicationService.getById(app_id);
			app_type=app.getApp_type();	
			
		} 
		Map<String, Object> retMap=new HashMap<String, Object>();
		retMap.put("data", list);
		retMap.put("app_type", app_type);
		return AjaxMap.success(retMap);
	}
	
	/**
	 * 拖动排序,暂时疲敝功能
	 * @return
	 */
	@PostMapping("/updateActionSort")
	@ApiOperation(value = "拖动排序", notes = "作者：LuZhongren")
	public Map<String, Object> updateActionSort(@RequestBody Map<String, Object> map) {
		if(map==null) AjaxMap.failed(MessageUtils.message("search.not.exist"));
		Map<String, Object> retMap=new HashMap<String, Object>();
		//currentId,preId,nextId,menu_id
		if(!map.containsKey("preId")) {
			retMap.put("pre",0);
			return AjaxMap.success(retMap);
		}
		Long preActionId=Long.parseLong(map.get("preId").toString());
		
		Map<String, Object> sortMap=sysActionService.getMap(new QueryWrapper<SysAction>().eq("id", preActionId).select("sortid"));
		
		retMap.put("pre",sortMap.get("sortid"));
		
		return AjaxMap.success(retMap);
	
	}
	
	/**
	 * @explain 修改
	 * @param 对象参数：SysAction
	 * @return Boolean
	 * @author LuZhongren
	 * @time 2022年1月27日
	 */
	@PostMapping("/quckCreateAction")
	@ApiOperation(value = "修改", notes = "作者：LuZhongren")
	public Map<String, Object> quckCreateAction(@RequestBody  Map<String, Object> map) {
		if(map==null) return AjaxMap.failed(MessageUtils.message("input.parameter.error"));
		List<Integer> actions=StringUtils.castList(map.get("actions"), Integer.class);//(List<Integer>)map.get("actions");
		Long menu_id=Long.parseLong(map.get("menu_id").toString());
		Map<String, Object> retMap=new HashMap<String, Object>();
		boolean exits_status=false;
		for(int i=0;i<actions.size();i++) {
			for(Map<String, Object> action:Parameters.actionList()) {
				if(actions.get(i)==(Integer)action.get("type")) {
					long count=sysActionService.count(new QueryWrapper<SysAction>().eq("menu_id", menu_id).eq("action_name", action.get("action_name")));
					if(count==0) {
						SysAction newAction=new SysAction();
						try {
							BeanUtils.copyProperties2Bean(action, newAction);
							newAction.setMenu_id(menu_id);
							sysActionService.save(newAction);
						} catch (InvocationTargetException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IntrospectionException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}else {
						exits_status=true;
					}
				}
			}
		}
		retMap.put("exits_status", exits_status);
		return AjaxMap.success(retMap);
				

		
	}

}